package cn.net.wangyixinwen.mvvm.activity;


import android.view.LayoutInflater;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import java.util.ArrayList;
import java.util.List;

import cn.net.wangyixinwen.R;
import cn.net.wangyixinwen.databinding.ActivityMainBinding;
import cn.net.wangyixinwen.mvvm.fragment.TypeFragment;
import cn.net.wangyixinwen.mvvm.fragment.HomeFragment;
import cn.net.wangyixinwen.mvvm.fragment.JXFragment;
import cn.net.wangyixinwen.mvvm.fragment.MineFragment;
import cn.net.wangyixinwen.mvvm.fragment.VideoFragment;
import cn.net.wangyixinwen.mvvm.vm.BaseViewModel;

/**
 * 主页
 */
public class MainActivity extends BaseActivity {

    private ActivityMainBinding viewBinding;

    private List<Fragment> fragmentList = new ArrayList<>();

    private int position = 0;

    @Override
    protected BaseViewModel viewModel() {
        return null;
    }

    @Override
    protected void initView() {
        viewBinding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(viewBinding.getRoot());
        fragmentList.add(new HomeFragment());
        fragmentList.add(new JXFragment());
        fragmentList.add(new TypeFragment());
        fragmentList.add(new VideoFragment());
        fragmentList.add(new MineFragment());

        viewBinding.llHome.setOnClickListener(view -> {
            if (position != 0) {
                showFragment(0);
            }
        });

        viewBinding.llJingxuan.setOnClickListener(view -> {
            if (position != 1) {
                showFragment(1);
            }
        });


        viewBinding.llFenlei.setOnClickListener(view -> {
            if (position != 2) {
                showFragment(2);
            }
        });

        viewBinding.llVideo.setOnClickListener(view -> {
            if (position != 3) {
                showFragment(3);
            }
        });

        viewBinding.llMine.setOnClickListener(view -> {
            if (position != 4) {
                showFragment(4);
            }
        });


        showFragment(0);
    }

    private void showFragment(int position) {
        this.position = position;
        FragmentTransaction tran = getSupportFragmentManager().beginTransaction();
        Fragment fragment = fragmentList.get(position);
        for (Fragment f : fragmentList) {
            if (f.isAdded()) {
                tran.hide(f);
            }
        }
        if (!fragment.isAdded()) {
            tran.add(R.id.fragment_content, fragment);
        }
        tran.show(fragment);
        tran.commitAllowingStateLoss();
    }
}

